<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of PHP-MELANGE.
 *
 * PHP-MELANGE is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-MELANGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-MELANGE; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    Melange
 * @package     php-melange
 * @subpackage  cms
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 *
 */

require_once("mvc/action/Action.php");
require_once("cms/core/om/BinaryFilePeer.php");

class FileAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("FileAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        if($this->log->isDebugEnabled())
            $this->log->debug("Executing FileAction");

        if($mapping->getPath() == "/image") {

            require_once("cms/core/om/Image.php");

            $c = new Criteria();
            $c->clearSelectColumns();
            $c->addSelectColumn(ImagePeer::BINARY_FILE_ID);
            $c->add(ImagePeer::IMAGE_ID, $form->getId());
            $c->setLimit(1);

            $rs = ImagePeer::doSelectRS($c);

            if($rs->next()) {
                $form->setId($rs->getInt(1));
            }

        }

        $c = new Criteria();
        $c->clearSelectColumns();
        $c->addSelectColumn(BinaryFilePeer::MODIFIED_DATE);
        $c->add(BinaryFilePeer::BINARY_FILE_ID, $form->getId());
        $c->setLimit(1);

        $rs = BinaryFilePeer::doSelectRS($c);

        if($rs->next()) {

            $modified = $rs->getDate(1, null);

            $this->log->debug($modified . " : " . gmdate("D, d M Y H:i:s T", $modified) . " : " . $_SERVER["HTTP_IF_MODIFIED_SINCE"]);

            $response->getOutputBuffer()->reset();
            $response->getOutputBuffer()->close();

            ini_set("zlib.output_compression", 0);

            // Check the HTTP_IF_NONE_MATCH and If-Modified-Since headers
            if(
                !empty($_SERVER["HTTP_IF_NONE_MATCH"]) &&
                (strpos($_SERVER["HTTP_IF_NONE_MATCH"], "amsco{$form->getId()}")) &&
                (gmdate("D, d M Y H:i:s T", $modified) == $_SERVER["HTTP_IF_MODIFIED_SINCE"])) {

                if($this->log->isDebugEnabled())
                    $this->log->debug("They already have the most up to date copy of the file.");

                $response->getOutputBuffer()->close();

                // They already have the most up to date copy of the file so tell them
                header("HTTP/1.1 304 Not Modified");exit();
                header("Cache-Control: private");

                // Turn off the no-cache pragma, expires and content-type header
                header("Pragma: ");
                header("Expires: ");
                header("Content-Type: ");
                header("Content-Length: ");

                // The Etag must be enclosed with double quotes
                header("ETag: \"amsco".$form->getId()."\"");


            } else {

                // They need a new copy of the file so open it up
                $binaryFile = BinaryFilePeer::retrieveByPk($form->getId());

                // Set the content-type to something like image/jpeg and set the length
                header("Content-Type: ".$binaryFile->getContentType());
                header("Content-Length: ".$binaryFile->getFileSize());

                // Change php’s default caching mechanisms
                header("Cache-Control: private");
                header("Pragma: ");
                header("Expires: ");

                // Send the browser the last modified date and etag so they can cache it
                header("Last-Modified: ".gmdate('D, d M Y H:i:s T', $modified));
                header("ETag: \"amsco".$form->getId()."\"");

                if($mapping->getPath() == "/download") {

                    if($this->log->isDebugEnabled())
                        $this->log->debug("Downloading file : ".$binaryFile->getFileName());
                    header("Content-Description: File Transfer");
                    header("Content-Disposition: attachment; filename=".(eregi("msie", $_SERVER['HTTP_USER_AGENT']) ? rawurlencode($binaryFile->getFileName()) : $binaryFile->getFileName()));
                    header("Content-Transfer-Encoding: binary");

                } else if($mapping->getPath() == "/image") {

                    if($this->log->isDebugEnabled())
                        $this->log->debug("Displaying image : ".$binaryFile->getFileName());

                     header("Content-Disposition: inline; filename=amsco".$form->getId().".jpg");

                }

                echo $binaryFile->getFileData()->getContents();


            }

            exit();

        }

    }

}
?>